package controllers

import (
	"tms-server/gin/models"

	"strconv"

	"tms-server/env"

	"tms-server/utils"

	"github.com/gin-gonic/gin"
)

type AuthControllers struct{}

var AuthContrl = new(AuthControllers)

func (control *AuthControllers) Query(c *gin.Context) (res interface{}, e Error) {
	module := c.Query("module")
	authes, err := models.FindAuthes(module)
	if err != nil {
		return nil, GenError(err)
	}
	data := make([]map[string]interface{}, 0)
	for _, auth := range authes {
		info := map[string]interface{}{
			"id":     auth.Id,
			"name":   auth.Name,
			"module": auth.Module,
			"page":   auth.Page,
			"button": auth.Button,
		}
		data = append(data, info)
	}
	res = data
	return
}

func (control *AuthControllers) Get(c *gin.Context) (res interface{}, e Error) {
	page := c.Query("page")
	if page == "" {
		return nil, GenErrorMsg("参数错误")
	}
	found := false
	for _, pages := range env.Authes {
		for _, p := range pages {
			if p == page {
				found = true
			}
		}
	}
	if !found {
		return nil, GenErrorMsg("页面未找到")
	}
	auth, err := models.FindAuth(0, page)
	if err != nil {
		return nil, GenError(err)
	}
	res = auth
	return
}

func (control *AuthControllers) Create(c *gin.Context) (res interface{}, e Error) {
	name := c.PostForm("name")
	module := c.PostForm("module")
	page := c.PostForm("pa")
	button := c.PostForm("button")
	if name == "" {
		return nil, GenErrorMsg("参数错误.")
	}
	utils.Info(page)
	e = control.check(module, page)
	if e.ErrCode != 0 {
		return nil, e
	}
	auth := &models.Authority{
		Name:   name,
		Module: module,
		Page:   page,
		Button: button,
	}
	err := auth.Create()
	if err != nil {
		return nil, GenError(err)
	}
	res = auth.Id
	return
}

func (control *AuthControllers) Update(c *gin.Context) (res interface{}, e Error) {
	id, _ := strconv.ParseInt(c.PostForm("id"), 10, 64)
	if id <= 0 {
		return nil, GenErrorMsg("参数错误")
	}
	auth, err := models.FindAuth(id, "")
	if err != nil {
		return nil, GenError(err)
	}
	name := c.PostForm("name")
	if name != "" {
		auth.Name = name
	}
	module := c.PostForm("module")
	if module != "" {
		auth.Module = module
	}
	page := c.PostForm("page")
	if page != "" {
		auth.Page = page
	}
	err = auth.Update()
	if err != nil {
		return nil, GenError(err)
	}
	res = "ok"
	return
}

func (control *AuthControllers) Delete(c *gin.Context) (res interface{}, e Error) {
	id, _ := strconv.ParseInt(c.Query("id"), 10, 64)
	if id <= 0 {
		return nil, GenErrorMsg("参数错误")
	}
	auth := &models.Authority{
		Id: id,
	}
	err := auth.Del()
	if err != nil {
		return nil, GenError(err)
	}
	res = "ok"
	return
}

func (control *AuthControllers) check(module, page string) (e Error) {
	if module == "" || page == "" {
		utils.Info(module, page)
		return GenErrorMsg("参数错误")
	}
	pages, found := env.Authes[module]
	if !found || len(pages) == 0 {
		return GenErrorMsg("模块未找到")
	}
	found = false
	for _, p := range pages {
		if p == page {
			found = true
		}
	}
	if !found {
		return GenErrorMsg("页面未找到")
	}
	return
}
